import url, { mainUrl } from "../utils/url.js"
import util from "../utils/util.js"


let myUrl = require("../utils/url.js")

let requests = require("../utils/requests.js")

/**
 * 获取课程列表
 */
export function courseList(){
  return requests.fatch({
    load: 1,
    url: myUrl.mainUrl + "course/"
  })
}

/**
 * 获取指定课程id详情
 * @param {*} courseId 课程id
 */
export function courseDetial(courseId){
  console.log(courseId)
  return requests.fatch({
    load: 1,
    url: myUrl.mainUrl + "course/" + courseId + "/"
  })
}

/**
 * 获取手机验证码
 * @param {手机号} mobile 
 */
export function mobileCode(mobile){
  return requests.fatch({
    load: 1,
    method:"POST",
    data:{
      mobile: mobile
    },
    url: myUrl.mainUrl + "code/"
  })
}


/**
 * 
 * @param {手机号} mobile 
 * @param {验证码} code 
 */
 export function userLogin(mobile, code){
   wx.login({
     success:function(res){
       console.log(res)
       // 获取openId
       requests.fatch({
         load: 1,
         method:"POST",
         data:{
           code: res.code
         },
         url: myUrl.mainUrl + "openid/"
       }).then(res=>{
         let open_id = res.data.openid;
         // 获取用户基本信息
         wx.getUserInfo({
           success:function(res){
            let userInfo = JSON.parse(res.rawData)
             // 请求后台登录
            requests.fatch({
              data:{
                "open_id": open_id,
                "nick_name": userInfo.nickName,
                "mobile": mobile, //手机号
                "code": code, //验证码
                "gender": util.gender[userInfo.gender],
                "avatar_url": userInfo.avatarUrl
              },
              load: 1,
              method:"POST",
              url: myUrl.mainUrl + "userlogin/"
            }).then(res=>{
              wx.hideLoading()
              console.log(res)
              if(res.statusCode == 200 || res.statusCode == 201){
                // 验证成功 验证码输入成功执行
                //将token存储到wx.storage
                wx.setStorageSync('token', res.data.token)
                //发起请求 拿到用户的基本信息存储到本地缓存
                requests.fatch({
                  header: {'Authorization': "JWT " + res.data.token},
                  load: 0,
                  method:"GET",
                  url: myUrl.mainUrl + "userinfo/"
                }).then(res=>{
                  //存储返回值到本地缓存
                  wx.setStorageSync('userInfo', res.data)
                  //加载用户收藏的课程到缓存
                  favPaperList().then(res=>{
                    console.log(res)
                    wx.setStorageSync("userFavPaper", res.data)
                  })

                  wx.showToast({
                    title: '登录成功',
                    icon: 'none',
                    duration: 3000
                  })
                  wx.hideLoading()
                  //跳转到首页
                  wx.switchTab({
                    url: '/pages/user/user',
                  })
                })
              }else{
                console.log(res)
                wx.showToast({
                  title: res.data.code[0],
                  icon: 'none',
                  duration: 2000
                })
              }
            }, error=>{
              console.log(error)
              wx.hideLoading()
              wx.showToast({
                title: '登录失败，请重试',
                icon: 'none',
                duration: 3000
              })
            })
           },
           fail:function(res){
             console.log(res)
             wx.hideLoading()
             wx.showToast({
              title: '用户信息获取失败',
              icon: 'none',
              duration: 3000
            })
           }
         })
       })
     },
     fail:function(res){
      wx.showToast({
        title: 'code获取失败',
        icon: 'none',
        duration: 3000
      })
     }
   })
 }

/**
 * 获取用户所有课程
 */
 export function userCourse(){

  let token = "JWT " + wx.getStorageSync("token")
  return requests.fatch({
    header: {'Authorization': token},
    load: 0,
    url: myUrl.mainUrl + "usercourse/"
  })
  
 }

 /**
  * 加入购物车
  */

  export function addShoppingCart(course_id){
    try{
      if(!hasToken()){
        wx.showToast({
          title: '未登录',
          icon: 'none',
          duration: 2000
        })
      }
      return requests.fatch({
        load: 1,
        url: myUrl.mainUrl + "shoppingcart/",
        header: { "Authorization": "JWT " + wx.getStorageSync('token') },
        method: "POST",
        data: {
          course: course_id
        }
      })
    }catch(error){
      console.log(error)
      wx.showToast({
        title: '服务器开小差了',
        icon: 'none',
        duration: 2000
      })
    }
  }

  /**
   * 获取购物车中所有商品
   */
  export function shoppingCart(){
    try{
      if(!hasToken()){
        wx.showToast({
          title: '未登录',
          icon: 'none',
          duration: 2000
        })
      }
      return requests.fatch({
        load: 1,
        url: myUrl.mainUrl + "shoppingcart/",
        header: { "Authorization": "JWT " + wx.getStorageSync('token') },
        method: "GET"
      })
    }catch(error){
      console.log(error)
      wx.showToast({
        title: '服务器开小差了',
        icon: 'none',
        duration: 2000
      })
    }
  }

  /**
   * 移除购物车商品
   */
  export function shoppingCartDelete(course_id){
    try{
      if(!hasToken()){
        wx.showToast({
          title: '未登录',
          icon: 'none',
          duration: 2000
        })
      }
      return requests.fatch({
        load: 0,
        url: myUrl.mainUrl + "shoppingcart/" + course_id + "/",
        method: "delete",
        header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      })
    }catch(error){
      console.log(error)
      wx.showToast({
        title: '服务器开小差了',
        icon: 'none',
        duration: 2000
      })
    }
  }

  /**
   * 修改购物车的选中情况
   * @param {购物车编号} course_id
   */
  export function shoppingCartSelected(id){
    try{
      if(!hasToken()){
        wx.showToast({
          title: '未登录',
          icon: 'none',
          duration: 2000
        })
      }
      return requests.fatch({
        load: 0,
        url: myUrl.mainUrl + "shoppingcart/" + id + "/",
        method:"PUT",
        header: { "Authorization": "JWT " + wx.getStorageSync('token') }
      })
    }catch(error){
      console.log(error)
      wx.showToast({
        title: '服务器开小差了',
        icon: 'none',
        duration: 2000
      })
    }
  }

  /**
   * 创建订单
   * @param {用户手机号} singer_mobile 
   * @param {优惠码} post_script 
   */
  export function createOrder(singer_mobile, post_script, order_mount){
    try{
      if(!hasToken()){
        wx.showToast({
          title: '未登录',
          icon: 'none',
          duration: 2000
        })
      }
      return requests.fatch({
        load:  1,
        url: myUrl.mainUrl + "order/",
        method: "POST",
        data:{
          singer_mobile: singer_mobile,
          post_script: post_script,
          order_mount: order_mount
        },
        header: { "Authorization": "JWT " + wx.getStorageSync('token') }
      })
    }catch(error){
      console.log(error)
      wx.showToast({
        title: '服务器开小差了',
        icon: 'none',
        duration: 2000
      })
    }
  }

  /**
   * 添加用户收藏
   * @param {课程id} course_id 
   */
  export function addUserFav(course_id){
    if(!hasToken()){
      wx.showToast({
        title: '未登录',
        icon: 'none',
        duration: 2000
      })
    }
    return requests.fatch({
      load: 1,
      url: myUrl.mainUrl + "userfav/",
      data:{
        course: course_id
      },
      method:"POST",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }

  /**
   * 移除用户收藏
   */
  export function removeUserFav(course_id){
    if(!hasToken()){
      wx.showToast({
        title: '未登录',
        icon: 'none',
        duration: 2000
      })
    }
    return requests.fatch({
      load: 1,
      url: myUrl.mainUrl + "userfav/" + course_id + "/",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      method: "DELETE"
    })
  }

  /**
   * 获取用户收藏列表
   */
  export function userFav(){
    if(!hasToken()){
      wx.showToast({
        title: '未登录',
        icon: 'none',
        duration: 2000
      })
    }
    return requests.fatch({
      load: 0,
      url: myUrl.mainUrl + "userfav/",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      method: "GET"
    })
  }

  /**
   * 开始支付
   */
  export function startPay(orderInfo){
    let that = this

    return requests.fatch({
      load: 0,
      url: myUrl.mainUrl + "orderpay/",
      method:"POST",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      data:{
        order_id:orderInfo['order_id'],
        order_sn:orderInfo['order_sn']
      }
    }).then(res=>{
      console.log(res)
      let result = JSON.parse(res.data.data)
      wx.requestPayment({
        appId: result.appId,
        nonceStr: result.nonceStr,
        package: result.package,
        paySign: result.paySign,
        timeStamp: result.timeStamp,
        signType: result.signType,
        success:function(res){
          console.log(res)
          wx.showToast({
            title: '支付成功',
            icon: 'none',
            duration: 2000
          })
          payCallBack(orderInfo)
        },
        fail:function(res){
          console.log(res)
          wx.showToast({
            title: '支付取消',
            icon: 'none',
            duration: 2000
          })
        }
      })
    },err=>{
      wx.showToast({
        title: '支付调用失败',
        icon: 'none',
        duration: 2000
      })
    })
  }

  function payCallBack(orderInfo){
    console.log(orderInfo)
    wx.request({
      url:myUrl.mainUrl + "payback/",
      method:"POST",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      data:{
        order_id:orderInfo.id,
        order_sn:orderInfo.order_sn
      },
      success:function(res){
        if(res.data.code == 200){
          console.log(res)
          wx.redirectTo({
            url: '../paySuccess/paySuccess',
          })
        }else{
          wx.showToast({
            title: '支付失败',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }

  /**
   * 获取所有订单
   */
  export function getAllOrder(){
    return requests.fatch({
      load: 1,
      url: myUrl.mainUrl + "order/",
      method:"GET",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }

  /**
   * 获取指定支付状态的订单
   * @param {订单状态} pay_status 
   */
  export function getStatusOrder(pay_status){
    return requests.fatch({
      load: 1,
      url: myUrl. mainUrl + "order/",
      method:"GET",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      data:{
        pay_status: pay_status
      }
    })
  }

  /**
   * 删除订单
   */
  export function deleteOrder(order_id){
    return requests.fatch({
      load: 0,
      url: myUrl.mainUrl + "order/" + order_id + "/",
      method:"DELETE",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }

  /**
   * 订单详情
   */
  export function orderDetial(order_id){
    return requests.fatch({
      load: 1,
      url: myUrl.mainUrl + "order/" + order_id + "/",
      method: "GET",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }

  /**
   * 订单评价提交
   */
  export function evaluateUpload(order_sn, orderEvaluateList){

    return requests.fatch({
      url: myUrl.mainUrl + "evaluate/",
      load: 1,
      data:{
        order_sn: order_sn,
        orderEvaluateList: orderEvaluateList
      },
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      method: "POST"
    })

  }

  /**
   * 
   * @param {手机号码} singer_mobile 
   * @param {课程id} course_id 
   */
  export function singlePay(singer_mobile, course_id){
    return requests.fatch({
      url: myUrl.mainUrl + "singleorder/",
      load: 1,
      data: {
        singer_mobile: singer_mobile,
        course_id: course_id
      },
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
      method: "POST"
    })
  }


  /**
   * 验证是否有token
   */
   function hasToken(){
    let token = wx.getStorageSync('token')
    console.log(token)
    if(token === "") return false;
    return true
   }


   /**
    * 获取用户购买的面试题
    */
   export function getUserPaper(){
    return requests.fatch({
      load: 1,
      url: myUrl.mainUrl + "userpaper/",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }


  /**
   * 判断是否购买该课程
   */
  export function userHasCourse(course_id){
    return requests.fatch({
      url: myUrl.mainUrl + "havecourse/" + course_id + "/",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }

  /**
   * 获取收藏的试卷
   */
  export function favPaperList(){
    return requests.fatch({
      url: myUrl.mainUrl + "favpaper",
      header: { "Authorization": "JWT " + wx.getStorageSync('token') },
    })
  }
